<template>
	<view>
		<view class="newsList">
			<view class="" @click="openChat">打开</view>
			<view class="" @click="closeChat">关闭</view>
			
			<view class="item" v-for="(item,index) in list" :key="index">
				
				<text>{{item}}</text>
				
			</view>
			<view class="bottom">
				<u-input
				    class=""
				    v-model="message"
				    placeholder="请输入"
				>
				<!-- <u-button type="primary" shape="circle" @click="sendChat()">
				    发送
				</u-button> -->
				<u-button
										@tap="sendChat"
										text="发送"
										type="success"
										size="mini"
									></u-button>
									</u-input>
			</view>
			
		</view>
	</view>
</template>

<script>

	export default {
		data() {
			return {
				socketOpen: false,
				socketMsgQueue: [],
				
				list:[],
				message: ''
			}
		},
		methods: {
			
			

			// var socketOpen = false;
			// var socketMsgQueue = [];
			
			
			openChat(){
				let that = this;
				uni.connectSocket({
				  url: 'ws://127.0.0.1:2345/socket'
				});
				uni.onSocketOpen(function (res) {
				  console.log('WebSocket连接已打开！');
				  let msg = 'WebSocket连接已打开！';
				  that.list.push(msg);
				});
				
				uni.onSocketError(function (res) {
				  console.log('WebSocket连接打开失败，请检查！');
				  let msg = 'WebSocket连接打开失败，请检查！';
				  that.list.push(msg);
				});
				uni.onSocketMessage(function (res) {
				  console.log('收到服务器内容：' + res.data);
				  let msg = '收到：' + res.data;
				  that.list.push(msg);
				});
			},
			sendChat(){
				let msg = this.message;
				this.message = '';
				uni.sendSocketMessage({
				  data: msg
				});
				this.list.push('发送：' + msg);

			},
			closeChat(){
				uni.onSocketOpen(function () {
				  uni.closeSocket();
				});
				uni.onSocketClose(function (res) {
				  console.log('WebSocket 已关闭！');
				  let msg = 'WebSocket 已关闭！';
				  that.list.push(msg);
				});
			}


		},
		onLoad() {
			this.openChat();
			// this.getData()
		}
	}
</script>

<style>
	.newsList{
		width: 90%;
		margin: 10px;
		.newsItem{
			padding:5px  0;
			border-bottom: 1px solid #ccc;
		}
	}
	.bottom{
		position: fixed;
		bottom: 0;
		left: 0;
	}
</style>
